﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Web.DynamicData;
using System.Web.UI;
using System.Web.UI.WebControls;
using MineSolutions.ExtendedQueryableFilter.Library;

namespace MineSolutions.ExtendedQueryableFilter.WebDomainApplication
{
    public partial class DateFilter : System.Web.DynamicData.QueryableFilterUserControl
    {
        public override IQueryable GetQueryable(IQueryable source)
        {
            String selectedValue = TextBox1.Text;
            DateTime selectedDateTime;
            if (!String.IsNullOrWhiteSpace(selectedValue))
            {
                if (DateTime.TryParse(selectedValue, out selectedDateTime))
                {
                    switch (this.GetFilterType())
                    {
                        case NumericFilterType.LessThan:
                            return FilterQueryable.ApplyDateLessThanFilter(source, Column.Name, selectedValue);
                        case NumericFilterType.LessThanOrEqual:
                            return FilterQueryable.ApplyDateLessThanOrEqualFilter(source, Column.Name, selectedValue);
                        case NumericFilterType.GreaterThan:
                            return FilterQueryable.ApplyDateGreaterThanFilter(source, Column.Name, selectedValue);
                        case NumericFilterType.GreaterThanOrEqual:
                            return FilterQueryable.ApplyDateGreaterThanOrEqualFilter(source, Column.Name, selectedValue);
                        case NumericFilterType.Equals:
                        default:
                            return FilterQueryable.ApplyDateEqualityFilter(source, Column.Name, selectedValue);
                    }
                }
            }

            return source;
        }

        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {
            OnFilterChanged();
        }

        protected void FilterRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            OnFilterChanged();
        }

        private NumericFilterType GetFilterType()
        {
            if (this.EqualsRadioButton.Checked)
                return NumericFilterType.Equals;
            else if (this.LessThanRadioButton.Checked)
                return NumericFilterType.LessThan;
            else if (this.LessThanOrEqualRadioButton.Checked)
                return NumericFilterType.LessThanOrEqual;
            else if (this.GreaterThanRadioButton.Checked)
                return NumericFilterType.GreaterThan;
            else if (this.GreaterThanOrEqualRadioButton.Checked)
                return NumericFilterType.GreaterThanOrEqual;

            return NumericFilterType.Equals;
        }
    }
}